import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/servletControllRegiste")
public class servletControllRegiste extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("register.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username.length() < 6 || password.length() < 6) {
            request.setAttribute("error", "用户名/密码需大于等于6位");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        if(username.length() > 30 || password.length() > 30) {
            request.setAttribute("error", "用户名/密码需小于等于30位");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        if(!username.matches("^[a-zA-Z0-9]+$") || !password.matches("^[a-zA-Z0-9]+$")) {
            request.setAttribute("error", "密码需由字母、数字组成");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        User user = new User(username, password);
        UserDao userDao = new UserDao();

        // 检查用户名是否已经存在
        if (userDao.isUsernameExists(username)) {
            request.setAttribute("error", "用户名已经存在！");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        userDao.registerUser(user);

        request.setAttribute("success", "注册成功");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
}

